﻿using Dapper;
using SIG.DAL.Dapper.Model;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SIG.DAL.Dapper.Repositories
{
    public class LogRepository
    {
        private DbConnection _connection;
        public IEnumerable<Log> GetListPagedItems(int pageIndex, int pageSize, DateTime? startDate, DateTime? expireDate, string level, out int totalCount)
        {
            IEnumerable<Log> result;
            using (_connection = Utilities.GetOpenConnection())
            {
                var sql = "WHERE 1=1 ";
                if (startDate != null)
                {                  
                    sql = sql + " and Date >= @StartDate ";
                }

                if (expireDate != null)
                {                  
                    sql = sql + " and Date >= @ExpireDate ";
                }
                if (!string.IsNullOrEmpty(level))
                {
                    sql = sql + " and Level = @Level ";
                }

                totalCount = _connection.RecordCount<Log>(sql, new { StartDate = startDate, ExpireDate = expireDate , Level = level });
                result = _connection.GetListPaged<Log>(pageIndex, pageSize, sql, "Date desc", new { StartDate = startDate, ExpireDate = expireDate, Level = level });
            }
            return result;
        }

        public int Delete(Log model)
        {
            int result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Delete(model);
            }
            return result;
        }

        public int Delete(int id)
        {
            int result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Delete<Log>(id);
            }
            return result;
        }

        public int RemoveAll()
        {
            int result;
            using (_connection = Utilities.GetOpenConnection())
            {
              
                string deleteQuery = "DELETE FROM Logs";
                result = _connection.Execute(deleteQuery);
                
            }
            return result;
        }
    }
}
